import {importEmployeesApi} from '@/api/Employee'

export default {
    name: 'EmployeeImport',
    props: {
        value: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            uploading: false,
            selectedFile: null,
        }
    },
    computed: {
        visible: {
            get() {
                return this.value
            },
            set(val) {
                this.$emit('input', val)
            }
        }
    },
    methods: {
        handleClose() {
            this.selectedFile = null
            this.$refs.upload.clearFiles()
        },
        //文件选择变化时触发
        handleFileChange(file) {
            // 先清除之前的文件
            this.$refs.upload.clearFiles();
            this.$refs.upload.uploadFiles = [file];
            this.selectedFile = file.raw;
        },
        //提交上传
        async submitUpload() {
            if (!this.selectedFile) {
                this.$message.warning('请先选择文件')
                return
            }

            this.uploading = true

            try {
                const formData = new FormData()
                formData.append('file', this.selectedFile)
                const response = await importEmployeesApi(formData)

                // 检查响应内容类型
                const contentType = response.headers['content-type'] || ''
                if (contentType.includes('application/json')) {
                    // JSON响应,完全成功
                    this.$message.success('导入成功。')
                    this.$emit('importSuccess')
                } else if (contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
                    // Excel响应,部分失败
                    const blob = new Blob([response.data], { type: contentType })
                    const url = window.URL.createObjectURL(blob)
                    const link = document.createElement('a')
                    link.href = url
                    link.setAttribute('download', '导入失败记录.xlsx')
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link)
                    window.URL.revokeObjectURL(url)

                    this.$message.warning('导入完成，但有失败记录，已下载失败记录。')
                    // 通知刷新部分数据
                    this.$emit('importSuccess')
                } else {
                    // 未知响应类型
                    throw new Error('未知的响应类型')
                }
            } catch (error) {
                console.error('导入失败', error)
                this.$message.error('导入失败：' + (error.message || '系统错误'))
            } finally {
                this.uploading = false
            }
        }
    }
}
